package projetjee

import org.springframework.dao.DataIntegrityViolationException

import javax.servlet.http.HttpServletResponse
import org.codehaus.groovy.grails.plugins.springsecurity.SpringSecurityUtils
import org.springframework.security.authentication.AccountExpiredException
import org.springframework.security.authentication.CredentialsExpiredException
import org.springframework.security.authentication.DisabledException
import org.springframework.security.authentication.LockedException
import org.springframework.security.core.context.SecurityContextHolder as SCH
import org.springframework.security.web.WebAttributes
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
import grails.plugins.springsecurity.Secured


class RelationshipController {
	
	/**
	* Dependency injection for the springSecurityService.
	*/
	def springSecurityService
	
    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
	
    def index() {
        redirect(action: "list", params: params)
    }

    def list() {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [relationshipInstanceList: Relationship.list(params), relationshipInstanceTotal: Relationship.count()]
    }

    def create() {
        [relationshipInstance: new Relationship(params)]
    }

    def save() {
        def relationshipInstance = new Relationship(params)
        if (!relationshipInstance.save(flush: true)) {
            render(view: "create", model: [relationshipInstance: relationshipInstance])
            return
        }

		flash.message = message(code: 'default.created.message', args: [message(code: 'relationship.label', default: 'Relationship'), relationshipInstance.id])
        redirect(action: "show", id: relationshipInstance.id)
    }
	
	def addAmiGroupe() {
		def paramsRelationship = params['relation']
		def idRelationship = Integer.parseInt(paramsRelationship)
		def relationshipInstance = Relationship.findById(idRelationship)
		def userInstanceTemp = springSecurityService.getCurrentUser()
		/*
		println "La personne a ajouter est : "
		println userInstanceTemp.getUsername()
		println "Dans le groupe :"
		println "->Voici ce qu'on recupere : "
		println paramsRelationship
		println "->Voici la relation :"
		println relationshipInstance
		*/
		if( !relationshipInstance.getSubscribers().contains(userInstanceTemp.toString()) ){
			relationshipInstance.addToSubscribers(User.findByUsername(userInstanceTemp.getUsername()))
		}
		render(view: "show", model: [relationshipInstance: relationshipInstance])
	}
	
	def delAmiGroupe() {
		def paramsRelationship = params['relation']
		def idRelationship = Integer.parseInt(paramsRelationship)
		def relationshipInstance = Relationship.findById(idRelationship)
		/* On recupere l'utilisateur courant */
		def userInstanceTemp = springSecurityService.getCurrentUser()
		/* On recupere la relation courante */
		def userRelationshipInstance = Relationship.findById(idRelationship)
		
		for (item in relationshipInstance.getSubscribers()) { 
			if( item.toString() == userInstanceTemp.toString() ){
				println "il contient!!!"+item.toString()
				//item = "Carnard Boiteux"
			}
		}
		
		//relationshipInstance.getSubscribers().remove(userInstanceTemp.toString())
		render(view: "show", model: [relationshipInstance: relationshipInstance])
	}
	
    def show() {
        def relationshipInstance = Relationship.get(params.id)
        if (!relationshipInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'relationship.label', default: 'Relationship'), params.id])
            redirect(action: "list")
            return
        }

        [relationshipInstance: relationshipInstance]
    }

    def edit() {
        def relationshipInstance = Relationship.get(params.id)
        if (!relationshipInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'relationship.label', default: 'Relationship'), params.id])
            redirect(action: "list")
            return
        }

        [relationshipInstance: relationshipInstance]
    }

    def update() {
        def relationshipInstance = Relationship.get(params.id)
        if (!relationshipInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'relationship.label', default: 'Relationship'), params.id])
            redirect(action: "list")
            return
        }

        if (params.version) {
            def version = params.version.toLong()
            if (relationshipInstance.version > version) {
                relationshipInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'relationship.label', default: 'Relationship')] as Object[],
                          "Another user has updated this Relationship while you were editing")
                render(view: "edit", model: [relationshipInstance: relationshipInstance])
                return
            }
        }

        relationshipInstance.properties = params

        if (!relationshipInstance.save(flush: true)) {
            render(view: "edit", model: [relationshipInstance: relationshipInstance])
            return
        }

		flash.message = message(code: 'default.updated.message', args: [message(code: 'relationship.label', default: 'Relationship'), relationshipInstance.id])
        redirect(action: "show", id: relationshipInstance.id)
    }

    def delete() {
        def relationshipInstance = Relationship.get(params.id)
        if (!relationshipInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'relationship.label', default: 'Relationship'), params.id])
            redirect(action: "list")
            return
        }

        try {
            relationshipInstance.delete(flush: true)
			flash.message = message(code: 'default.deleted.message', args: [message(code: 'relationship.label', default: 'Relationship'), params.id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
			flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'relationship.label', default: 'Relationship'), params.id])
            redirect(action: "show", id: params.id)
        }
    }
}
